package GreedyAlgorithm;
/*
 * 合并区间
 */
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class lc56 {

    public int[][] merge(int[][] intervals) {
        List<int[]> res = new LinkedList<>();
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        int start = intervals[0][0];
        int mostRight = intervals[0][1];
        for (int i = 0; i < intervals.length; i++) {
            if (intervals[i][0] > mostRight) {
                res.add(new int[]{start, mostRight});
                start = intervals[i][0];
                mostRight = intervals[i][1];
            } else {
                mostRight = Math.max(mostRight, intervals[i][1]);
            }
        }
        res.add(new int[]{start, mostRight});
        return res.toArray(new int[res.size()][]);
    }

}
